# coding=utf-8
import datetime
import os
import sys
import time
import traceback

import pandas as pd
from loguru import logger

from cal_sh import get_sh_today_date
from mylib import update_all_csv
from send_email import send_email_plain


def run_sys(fw, cmd_str):
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    try:
        fw.write('{} start {}\n'.format(current_time, cmd_str))
        fw.flush()
        os.system(cmd_str)
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        fw.write('{} finished {}\n'.format(current_time, cmd_str))
        fw.flush()
    except Exception as e:
        logger.error(e)
        send_email_plain.send_plain(f'{cmd_str} Exception {e} {traceback.format_exc()}\n')


def get_stock_today_date(param):
    df = pd.read_csv(f'stocks/{param}')
    today_date = df.iloc[0]['trade_date']
    return today_date


# if __name__ == '__main__':
#     sh_today = get_sh_today_date()
#     today_0000001sz = get_stock_today_date('000001.SZ.csv')
#     today_0000002sz = get_stock_today_date('000002.SZ.csv')
#     # if (sh_today == today_0000001sz) or (sh_today == today_0000002sz):
#     print(today_0000001sz)
#     print(today_0000002sz)
#     print(sh_today)

current_date = str(datetime.datetime.now().date()).replace('-', '')
log_path = 'log_{}.txt'.format(current_date)
send_email_plain.send_plain('计算开始')
# 更新all.csv 一小时只能请求一次，默认不打开，必要时手动刷新
update_all_csv.run()

with open(log_path, 'a') as fw:
    # 下载所有
    run_sys(fw, 'python3 download_all.py')
    cnt = 10
    while cnt:
        # 更新上证，若不成功，等待一小时再次更新
        run_sys(fw, 'python3 update_sh.py')
        try:
            sh_today = get_sh_today_date()
        except Exception as e:
            logger.error(e)
        today_0000001sz = get_stock_today_date('000001.SZ.csv')
        today_0000002sz = get_stock_today_date('000002.SZ.csv')
        if (sh_today == today_0000001sz) or (sh_today == today_0000002sz):
            break
        # 等一小时再更新 sh
        send_email_plain.send_plain('update_sh.py 更新失败，一小时后重新更新')
        time.sleep(600)
        if sh_today > today_0000001sz and sh_today > today_0000002sz:
            # 上证更新了，股票未更新，下载所有股票
            send_email_plain.send_plain('update_sh.py更新成功，股票未更新，下载所有股票')
            run_sys(fw, 'python3 download_all.py')
        cnt -= 1
        if cnt == 0:
            send_email_plain.send_plain(
                f'计算完成,sh_today={sh_today},today_0000001sz={today_0000001sz},today_0000002sz={today_0000002sz}')
            sys.exit()

    # 计算最近10日，价格相对于最近一次10日顶涨跌幅趋势
    run_sys(fw, 'python3 a_recent_d.py')
    # 获取底部涨幅大于3,反弹预测
    run_sys(fw, 'python3 gen_down_up2.py')
    # 计算跌幅大于20%
    run_sys(fw, 'python3 a_recent_low_up.py')
    # 分析今日跌幅大于20%支数
    run_sys(fw, 'python3 a_recent_low_up_ana.py')
    # # 获取低于谷底排名-个股跌幅前20名
    run_sys(fw, 'python3 gen_low_rank_old.py 1')

    # 计算行业距离顶底距离
    # run_sys(fw, 'python3 a_recent_d_top_down.py')
    # 计算持仓股，下跌次数排序，累计跌幅排序，
    # run_sys(fw, 'python3 acc.py')
    # 计算行业 底部上涨/顶部下跌 次数排序
    # run_sys(fw, 'python3 aan.py 0 10 60')
    # run_sys(fw, 'python3 aatop_dis.py')
    # run_sys(fw, 'python3 aalow_dis.py')
    # 计算行业距离顶底距离
    # run_sys(fw, 'python3 a_count1.py')

    # 计算行业5日平均涨跌
    run_sys(fw, 'python3 a_pct5.py')
    run_sys(fw, 'python3 a_half.py')

    # 最近一次顶点到低点距离最大（最近涨得最厉害的）
    # run_sys(fw, 'python3 a_top_down_dis_rank.py')

    # 计算底部反弹
    # run_sys(fw, 'python3 a_cal_one.py')

time.sleep(60 * 10)
send_email_plain.send_plain('计算完成')
